/**
 * 进港少收行李列表
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import { Button, Modal, Input, DatePicker, Select, message, Checkbox } from 'antd';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';
import moment from 'moment';
import router from 'umi/router';
import { fileDownload } from '@/utils/downExcel';
import { useActivate } from 'react-activation';

import {
  getUserServiceCity,
  listUnderchargeLuggage,
  selectCityInfo,
  updateUnderchargeAccident,
  getPkgAccidentDetail,
  batchUpdateImg,
  listOverchargeLuggage,
  underchargeExport
} from './service';
import { Const } from '../Const';

import AuthComponent from '@/components/Authorized/AuthComponent';
import QuickRetrievalPopup from './components/QuickRetrievalPopup'; // 快速检索
import ExpressInfo from './components/ExpressInfo'; // 快递信息
import HistoryRecord from './components/HistoryRecord'; // 历史记录
import CompensationList from './components/CompensationList'; // 赔偿单列表
import AccidentReason from './components/AccidentReason'; // 事故单原因
import AllAccidentReason from './components/AllAccidentReason'; // 批量结案
import PicUpload from '../lessBaggageManagement/components/PicUpload';
import ShowPic from '../lessBaggageManagement/components/ShowPic';

const Option = Select.Option;
const { RangePicker } = DatePicker;

class PrivateData {
  static isFirst = true;
  static isFrom = true;
  // static hiddenData = {};
  static ownerType = 2;
  static isLessOrMore = 'less';
  static pkgNo = '';
  static toolBarRenderArr = [
    { text: '新增', value: '1', authCode: ['lessLuggage.basicPermissions'], disabled: false },
    { text: '修改', value: '2', authCode: ['lessLuggage.changeIncident', 'lessLuggage.changeAllIncident'], disabled: false },
    { text: '作废', value: '3', authCode: ['lessLuggage.deleteIncident', 'lessLuggage.deteltAllIncident'], disabled: false },
    { text: '快递', value: '4', authCode: ['lessLuggage.basicPermissions'], disabled: false },
    { text: '快速匹配', value: '5', authCode: ['lessLuggage.basicPermissions'], disabled: false },
    { text: '打印', value: '6', authCode: ['lessLuggage.basicPermissions'], disabled: false },
    { text: '归档打印', value: '7', authCode: ['lessLuggage.basicPermissions'], disabled: false },
    { text: '历史记录', value: '8', authCode: ['lessLuggage.basicPermissions'], disabled: false },
    { text: '转破损', value: '9', authCode: ['damagedLuggage.basicPermissions'], disabled: false },
    { text: '转内物缺失', value: '10', authCode: ['internalMissingLuggage.basicPermissions'], disabled: false },
    { text: '导出excel', value: '11', authCode: ['lessLuggage.basicPermissions'], disabled: false },
    { text: '批量结案', value: '12', authCode: ['lessLuggage.basicPermissions'], disabled: false },
  ];
}

const LessBaggageManagement = props => {

  const { location: { state } } = props;

  const actionRef = useRef();
  const ref = useRef();
  const searchRef = useRef();

  const [height, controlH] = useState(300); // table高度
  const [isCollapse, controlC] = useState(true);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 勾选索引
  const [selectedRows, setSelectedRows] = useState([]); // 勾选列

  const [userServiceCity, setUserServiceCity] = useState(''); // 用户默认服务航站

  const [quickRetrievalVisible, setQuickRetrievalVisible] = useState(false); // 快速检索弹窗

  const [expressInfoVisible, setExpressInfoVisible] = useState(false); // 快递信息弹窗

  const [historyRecordVisible, setHistoryRecordVisible] = useState(false); // 历史记录弹窗

  const [compensationListVisible, setCompensationListVisible] = useState(false); // 赔偿单列表弹窗

  const [accidentReasonVisible, setAccidentReasonVisible] = useState(false); // 事故单原因弹窗

  const [allAccidentReasonVisible, setAllAccidentReasonVisible] = useState(false); // 批量结案弹窗

  const [lostItemPicVisible, handleLostItemPicVisible] = useState(false); // PicUpload
  const [lostItemPicManageVisible, handleLostItemPicManageVisible] = useState(false); // ShowPic
  // 是否有图片
  const [lostItemPic, handleLostItemPicture] = useState({
    goodFileList: [],
    touristFileList: [],
    paperFileList: [],
    luggageFileList: []
  });
  // 初始图片数组
  const [originPicArr, handleOriginPicArr] = useState([]);

  const [itemData, setItemData] = useState({}); // 单个选择的值

  const [isLessOrMore, setIsLessOrMore] = useState('less');

  const [searchData, setSearchData] = useState({});

  // 表格是否有数据
  const [exportFlag, handleExportFlag] = useState(false);

  const [createStartTime, setCreateStartTime] = useState(moment().format(Const.format)); // 开始时间
  const [createEndTime, setCreateEndTime] = useState(moment().format(Const.format)); // 结束时间

  const [compensateType, setCompensateType] = useState(''); // 赔偿单类型 0临时 1结案

  const [accidentList, setAccidentList] = useState([]);

  const reloadReset = () => {
    setSelectedRows([]);
    setSelectedRowKeys([]);
    // actionRef.current.reload();
    ref.current.submit();
  };

  // 导出
  const { run: runUnderchargeExport } = useRequest(params => underchargeExport(params), {
    manual: true,
    onSuccess(res) {
      fileDownload(res, '进港少收行李管理');
    }
  })

  // 航站下拉列表
  const { data: selectCityData = [] } = useRequest(selectCityInfo);

  // 获取登录用户所属航站
  const { run: runGetUserServiceCity, loading: getUserServiceCityLoading } = useRequest(getUserServiceCity, {
    manual: true,
    onSuccess (res) {
      console.log(res, '获取登录用户所属航站');
      let data = res.serviceCity || '';
      setUserServiceCity(data);
      if (!ref.current.setFieldsValue) return;
      if (state?.accidentId) {
        ref.current.resetFields();
        setTimeout(() => {
          ref.current.setFieldsValue({
            accidentId: state?.accidentId || '',
          })
        }, 0);
      } else {
        setTimeout(() => {
          ref.current.setFieldsValue({
            flightDate: moment(),
            createStartTime: moment(),
            createEndTime: moment(),
            enterTerminal: data,
            serviceCity: data,
            status: ['0', '1', '2']
          })
        }, 0);
      }
    }
  });

  // 编辑事故单
  const { run: runUpdateUnderchargeAccident } = useRequest(data => updateUnderchargeAccident(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '编辑事故单');
      reloadReset();
    }
  });

  // 批量修改图片
  const { run: runBatchUpdateImg } = useRequest(data => batchUpdateImg(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '批量修改图片');
      reloadReset();
      handleLostItemPicManageVisible(false);
      handleLostItemPicVisible(false);
    }
  });

  // 事故单详情
  const { run: runGetPkgAccidentDetail } = useRequest(params => getPkgAccidentDetail(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '事故单详情');
      let data = res || {};
      let imgArr = data.pkgImgList || [];
      handleOriginPicArr(imgArr);
      let goodFileListData = imgArr.filter(item => {
        return item.oneType === 1
      });

      let touristFileListData = imgArr.filter(item => {
        return item.oneType === 2
      });

      let paperFileListData = imgArr.filter(item => {
        return item.oneType === 3
      });

      let luggageFileListData = imgArr.filter(item => {
        return item.oneType === 4
      });

      handleLostItemPicture({
        goodFileList: goodFileListData,
        touristFileList: touristFileListData,
        paperFileList: paperFileListData,
        luggageFileList: luggageFileListData,
      });

      handleLostItemPicManageVisible(true);
    }
  });

  // 编辑过后页面可见重新请求下列表数据
  useActivate(() => {
    if (Const.getIsNeedGetList(PrivateData.ownerType)) reloadReset();
    const isFromCompensate = sessionStorage.getItem('isFromCompensate') || '';
    if (isFromCompensate === '1' && state?.accidentId && !PrivateData.isFirst) {
      reloadReset();
      setTimeout(() => {
        if (ref.current.setFieldsValue) {
          ref.current.resetFields();
          ref.current.setFieldsValue({
            accidentId: state?.accidentId || '',
          })
        }
      }, 0);
    }
  });

  useEffect(() => {
    if (PrivateData.isFirst) {
      runGetUserServiceCity();
    }
    return () => {
      PrivateData.isFirst = true;
      PrivateData.isFrom = true;
      PrivateData.isLessOrMore = 'less';
      setIsLessOrMore('less');
    };
  }, []);

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 370);
    } else {
      controlH(document.body.clientHeight - 470);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isCollapse]);

  // rowSelection
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys);
    setSelectedRows(selectedRows);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  // 禁用今天之后的时间
  const disabledDate = useCallback((current) => {
    return current && current > moment().endOf('day');
  }, []);

  const disabledStartDate = useCallback((current) => {
    if (createEndTime) return current && (current > moment().endOf('day') || current > moment(createEndTime).endOf('day'));
    return current && current > moment().endOf('day');
  }, [createEndTime]);

  const disabledEndDate = useCallback((current) => {
    if (createStartTime) return current && (current > moment().endOf('day') || current < moment(createStartTime).startOf('day'));
    return current && current > moment().endOf('day');
  }, [createStartTime]);

  // 新增图片、改变图片
  const handleImgs = async fields => {

    let img = []
    let obj = {};

    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        imgInfo.relevance = itemData.accidentId
        img.push(imgInfo)
      })
    }

    // 修改后带有id(原本存在后台)的图片
    let lostItemPicIdArr = img.filter(item => {
      return item.id
    })
    // 新增加的图片
    let lostItemPicNotIdArr = img.filter(item => {
      return !item.id
    })
    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(lostItemPicIdArr).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    runBatchUpdateImg([...updateArr, ...lostItemPicNotIdArr])
  };

  // 删除图片
  const handleDelImgs = async fields => {
    let img = []
    let obj = {};
    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        img.push(imgInfo)
      })
    }

    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(img).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    runBatchUpdateImg([...updateArr]);
  }

  // 重置
  const onReset = useCallback(() => {
    setCreateStartTime('');
    setCreateEndTime('');
    setIsLessOrMore('less');
    PrivateData.isLessOrMore = 'less';
    PrivateData.isFirst = true;
    setTimeout(() => {
      ref.current.setFieldsValue({
        flightDate: moment(),
        createStartTime: moment(),
        createEndTime: moment(),
        enterTerminal: userServiceCity,
        serviceCity: userServiceCity,
        status: ['0', '1', '2']
      });
    }, 0)
  }, [userServiceCity]);

  // 跳转事故单详情
  const goToDetail = useCallback((item) => {
    router.push({
      pathname: Const.commonUrl + '/inPortBaggageManagement/accidentDetail',
      state: {
        accidentId: item.accidentId,
        ownerType: PrivateData.ownerType
      }
    });
  }, []);

  // 快速检索 - 打开
  const quickRetrievalOpen = useCallback(() => {
    setQuickRetrievalVisible(true);
  }, []);
  // 快速检索 - 取消
  const quickRetrievalCancel = useCallback(() => {
    setQuickRetrievalVisible(false);
  }, []);
  // 快速检索 - 提交
  const quickRetrievalSubmit = useCallback(() => {
    setQuickRetrievalVisible(false);
  }, []);

  // 快递信息 - 打开
  const expressInfoOpen = useCallback(() => {
    setExpressInfoVisible(true);
  }, []);
  // 快递信息 - 取消
  const expressInfoCancel = useCallback(() => {
    setExpressInfoVisible(false);
  }, []);
  // 快递信息 - 提交
  const expressInfoSubmit = useCallback(() => {
    setExpressInfoVisible(false);
  }, []);

  // 历史记录 - 打开
  const historyRecordOpen = useCallback(() => {
    setHistoryRecordVisible(true);
  }, []);
  // 历史记录 - 取消
  const historyRecordCancel = useCallback(() => {
    setHistoryRecordVisible(false);
  }, []);
  // 历史记录 - 提交
  const historyRecordSubmit = useCallback(() => {
    setHistoryRecordVisible(false);
  }, []);

  // 赔偿单列表 - 打开
  const compensationListOpen = useCallback((record, type) => {
    setCompensateType(type);
    setItemData(record);
    setCompensationListVisible(true);
  }, []);
  // 赔偿单列表 - 取消
  const compensationListCancel = useCallback(() => {
    setCompensateType('');
    setCompensationListVisible(false);
  }, []);
  // 赔偿单列表 - 提交
  const compensationListSubmit = useCallback(() => {
    compensationListCancel();
  }, []);

  // 事故单原因 - 打开
  const accidentReasonOpen = useCallback((text, record) => {
    if (+text !== 1) {
      setItemData(record);
      setAccidentReasonVisible(true);
    }
  }, []);
  // 事故单原因 - 取消
  const accidentReasonCancel = useCallback(() => {
    setAccidentReasonVisible(false);
  }, []);
  // 事故单原因 - 提交
  const accidentReasonSubmit = useCallback(() => {
    reloadReset();
    setAccidentReasonVisible(false);
  }, []);

  // 批量结案 - 打开
  const allAccidentReasonOpen = useCallback(() => {
    let arr = [];
    for (let item of selectedRows) {
      if ((item.status === '待处理' || item.status === '处理中') && (+item.isClosed === 0) && (+item.pkgStatus !== 1)) {
        arr.push(item);
      }
    }
    if (arr.length > 0) {
      setAccidentList(arr);
      setAllAccidentReasonVisible(true);
    } else {
      message.warning('所选的事故单里没有可以进行结案操作的')
    }
  }, [selectedRows]);
  // 批量结案 - 取消
  const allAccidentReasonCancel = useCallback(() => {
    setAllAccidentReasonVisible(false);
  }, []);
  // 批量结案 - 提交
  const allAccidentReasonSubmit = useCallback(() => {
    reloadReset();
    setAllAccidentReasonVisible(false);
  }, []);

  // 图片管理
  const imageManagemnt = useCallback((item) => {
    setItemData(item);
    runGetPkgAccidentDetail({
      accidentId: item.accidentId
    });
  }, []);

  // 顶部点击事件
  const headerTitleClick = useCallback((val) => {
    if (val === '1') {
      quickRetrievalOpen();
    }
    if (val === '2') {
      if (selectedRows.length === 1) {
        if (selectedRows[0].status === '待处理') {
          router.push({
            pathname: Const.commonUrl + '/inPortBaggageManagement/addEditIncident',
            state: {
              type: 'edit',
              ownerType: PrivateData.ownerType,
              isHave: false,
              accidentId: selectedRows[0].accidentId
            }
          });
        } else if (selectedRows[0].status === '已结案') {
          // 是否有全量修改的权限
          if (AuthComponent.getAuth('lessLuggage.changeAllIncident')) {
            router.push({
              pathname: Const.commonUrl + '/inPortBaggageManagement/addEditIncident',
              state: {
                type: 'edit',
                ownerType: PrivateData.ownerType,
                isHave: false,
                accidentId: selectedRows[0].accidentId
              }
            });
          } else {
            message.warning('请选择一个待处理的事故单进行修改');
          }
        } else {
          message.warning('请选择一个待处理的事故单进行修改');
        }
      }
    }
    if (val === '3') {
      if (selectedRows.length === 1) {
        if (AuthComponent.getAuth('lessLuggage.deteltAllIncident')) {
          Modal.confirm({
            title: '确认作废',
            content: '作废该条记录',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
              console.log('确认作废');
              runUpdateUnderchargeAccident({
                isCancel: 1,
                accidentId: selectedRows[0].accidentId,
                isAuth: AuthComponent.getAuth('lessLuggage.deteltAllIncident') ? 1 : 0
              })
            }
          });
        } else {
          if (selectedRows[0].status === '待处理') {
            Modal.confirm({
              title: '确认作废',
              content: '作废该条记录',
              okText: '确认',
              cancelText: '取消',
              onOk: () => {
                console.log('确认作废');
                runUpdateUnderchargeAccident({
                  isCancel: 1,
                  accidentId: selectedRows[0].accidentId,
                  isAuth: AuthComponent.getAuth('lessLuggage.deteltAllIncident') ? 1 : 0
                })
              }
            });
          } else {
            message.warning('请选择一个并且是待处理状态的事故单');
          }
        }
      }
    }
    if (val === '4') {
      if (selectedRows.length === 1 && (selectedRows[0].status === '处理中')) {
        setItemData(selectedRows[0]);
        expressInfoOpen();
      } else {
        message.warning('请选择一个处理中的事故单');
      }
    }
    if (val === '5') {
      if (selectedRows.length === 1 && (selectedRows[0].status === '待处理' || selectedRows[0].status === '处理中')) {
        setCreateStartTime('');
        setCreateEndTime('');
        setIsLessOrMore('more');
        PrivateData.isLessOrMore = 'more';
        ref.current.resetFields()
        PrivateData.pkgNo = selectedRows[0].pkgNo || '';
        ref.current.setFieldsValue({
          status: ['0', '2']
        });
        setTimeout(() => {
          if (searchRef.current) {
            searchRef.current.click();
          }
        }, 0)
      } else {
        message.warning('请选择一个待处理或者处理中的事故单');
      }
    }
    if (val === '6' || val === '7') {
      if (selectedRows.length === 1) {
        router.push({
          pathname: Const.commonUrl + '/inPortBaggageManagement/printPage',
          state: {
            accidentId: selectedRows[0].accidentId || '',
            type: val,
            ownerType: PrivateData.ownerType
          }
        });
      } else {
        message.warning('请选择一个事故单')
      }
    }
    if (val === '8') {
      if (selectedRows.length === 1) {
        setItemData(selectedRows[0]);
        historyRecordOpen();
      } else {
        message.warning('请选择一个事故单')
      }
    }
    if (val === '9') {
      if (selectedRows.length === 1 && (selectedRows[0].status === '待处理' || selectedRows[0].status === '处理中')) {
        if (selectedRows[0].outType) {
          message.warning('该事故单已经转过一次类型')
        } else {
          router.push({
            pathname: Const.commonUrl + '/inPortBaggageManagement/addEditIncident',
            state: {
              type: 'edit',
              ownerType: 1,
              isHave: false,
              accidentId: selectedRows[0].accidentId,
              isTurn: true,
            }
          });
        }
      } else {
        message.warning('请选择一个待处理或者处理中的事故单');
      }
    }
    if (val === '10') {
      if (selectedRows.length === 1 && (selectedRows[0].status === '待处理' || selectedRows[0].status === '处理中')) {
        if (selectedRows[0].outType) {
          message.warning('该事故单已经转过一次类型')
        } else {
          router.push({
            pathname: Const.commonUrl + '/inPortBaggageManagement/addEditIncident',
            state: {
              type: 'edit',
              ownerType: 6,
              isHave: false,
              accidentId: selectedRows[0].accidentId,
              isTurn: true,
            }
          });
        }
      } else {
        message.warning('请选择一个待处理或者处理中的事故单');
      }
    }
    if (val === '11') {
      if (!exportFlag) {
        message.warning('表格数据为空');
        return
      }
      runUnderchargeExport({...searchData});
    }
    if (val === '12') {
      if (selectedRows.length !== 0) {
        allAccidentReasonOpen();
      } else {
        message.warning('请选择至少一个事故单');
      }
    }
  }, [searchData, exportFlag, selectedRows]);

  // 临时赔偿、结案赔偿
  const goToAddEditCompensation = useCallback((text, record, type) => {
    if (text === '是') {
      // 已发起
      compensationListOpen(record, type)
    } else {
      // 未发起
      if (record.status === '待处理' || record.status === '处理中') {
        router.push({
          pathname: Const.commonUrl + '/inPortBaggageManagement/addEditCompensation',
          state: {
            status: 'add',
            type,
            itemData: record,
            detailData: {},
            ownerType: PrivateData.ownerType
          }
        });
      } else {
        message.warning('请选择待处理或者处理中的事故单')
      }
    }
  }, []);

  const columns = isLessOrMore === 'less' ? [
    {
      title: '事故单编号',
      dataIndex: 'accidentId',
      width: 200,
      fixed: 'left',
      render: (text, record) => (
        <Button
          type="link"
          style={{ padding: '0' }}
          disabled={!AuthComponent.getAuth('lessLuggage.basicPermissions')}
          onClick={() => goToDetail(record)}>
          {text}
        </Button>
      )
    },
    {
      title: '录入航站',
      dataIndex: 'enterTerminal',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          showSearch
          placeholder="请选择"
          value={value}
          onChange={onChange}
          optionFilterProp="children"
        >
          {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
        </Select>
      ),
    },
    {
      title: '服务航站',
      dataIndex: 'serviceCity',
      width: 100,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          showSearch
          placeholder="请选择"
          value={value}
          onChange={onChange}
          optionFilterProp="children"
        >
          {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
        </Select>
      ),
    },
    {
      title: '行李牌号',
      dataIndex: 'pkgNo',
      width: 120,
    },
    {
      title: '旅客姓名',
      dataIndex: 'paxName',
      width: 100,
    },
    {
      title: '证件类型',
      dataIndex: 'idType',
      width: 100,
      render: (text, record) => <span>{Const.idTypeMap[text]?.text || '-'}</span>,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          placeholder="请选择"
          value={value}
          onChange={onChange}
        >
          {Const.idTypeListForSearch.map(item => <Option key={item.value} value={item.value}>{item.label}</Option>)}
        </Select>
      ),
    },
    {
      title: '证件号',
      dataIndex: 'idNo',
      width: 200,
    },
    {
      title: '客票号',
      dataIndex: 'tktNo',
      width: 200,
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width: 80,
      renderFormItem: (_, { value, onChange }) => {
        return <Input
          onChange= {e => {
            let value = Const.formatFlightNo(e.target.value);
            onChange(value);
          }}
          value={value}
          allowClear
          maxLength={6}
          placeholder="3U" />;
      }
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={onChange}
            disabledDate={disabledDate}
            value={value}
          />
        );
      }
    },
    {
      title: '旅客航程',
      dataIndex: 'voyage',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '始发站',
      dataIndex: 'orgCityAirp',
      width: 80,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          showSearch
          placeholder="请选择"
          value={value}
          onChange={onChange}
          optionFilterProp="children"
        >
          {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
        </Select>
      ),
    },
    {
      title: '目的站',
      dataIndex: 'dstCityAirp',
      width: 80,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          showSearch
          placeholder="请选择"
          value={value}
          onChange={onChange}
          optionFilterProp="children"
        >
          {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
        </Select>
      ),
    },
    {
      title: '临时赔偿',
      dataIndex: 'tempPayment',
      width: 100,
      hideInSearch: true,
      render: (text, record) => (
        <Button
          type="link"
          style={{ padding: '0' }}
          disabled={!AuthComponent.getAuth('lessLuggage.basicPermissions')}
          onClick={() => goToAddEditCompensation(text, record, 0)}>
          {text === '是' ? '已发起' : '未发起'}
        </Button>
      )
    },
    {
      title: '结案赔偿',
      dataIndex: 'closePayment',
      width: 100,
      hideInSearch: true,
      render: (text, record) => (
        <Button
          type="link"
          style={{ padding: '0' }}
          disabled={!AuthComponent.getAuth('lessLuggage.basicPermissions')}
          onClick={() => goToAddEditCompensation(text, record, 1)}>
          {text === '是' ? '已发起' : '未发起'}
        </Button>
      )
    },
    {
      title: '图片管理',
      dataIndex: 'picture',
      width: 100,
      hideInSearch: true,
      render: (_, record) => (
        <Button
          type="link"
          disabled={!AuthComponent.getAuth('lessLuggage.basicPermissions')}
          style={{ padding: '0' }}
          onClick={() => imageManagemnt(record)}>
          图片管理
        </Button>
      )
    },
    {
      title: '结案状态',
      dataIndex: 'pkgStatus',
      width: 100,
      hideInSearch: true,
      render: (text, record) => (
        <Button
          type="link"
          style={{ padding: '0' }}
          disabled={!AuthComponent.getAuth('lessLuggage.basicPermissions')}
          onClick={() => {
            if ((record.status === '待处理' || record.status === '处理中') && (+record.isClosed === 0)) {
              accidentReasonOpen(text, record);
            } else {
              message.warning('该事故单不能进行结案操作');
            }
          }}>
          {+text === 1 ? '已结案' : '未结案'}
        </Button>
      )
    },
    {
      title: '事故原因',
      dataIndex: 'accidentReason',
      valueEnum: Const.accidentReasonMap,
      filters: false,
      width: 100,
      hideInSearch: true
    },
    {
      title: '赔偿总金额',
      dataIndex: 'payMoney',
      width: 120,
      hideInSearch: true
    },
    {
      title: '已赔付金额',
      dataIndex: 'receivePayment',
      width: 120,
      hideInSearch: true
    },
    {
      title: '未赔付金额',
      dataIndex: 'notPayment',
      width: 120,
      hideInSearch: true
    },
    {
      title: '录入人',
      dataIndex: 'createUser',
      width: 120,
      hideInSearch: true
    },
    // {
    //   title: '手工录入',
    //   dataIndex: 'dataType',
    //   width: 100,
    //   hideInSearch: true
    // },
    {
      title: '事故单状态',
      dataIndex: 'status',
      width: 120,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          placeholder="请选择"
          value={value}
          onChange={onChange}
          mode="multiple"
        >
          {Const.jieanStatusList.map(item => <Option key={item.value} value={item.value}>{item.label}</Option>)}
        </Select>
      ),
    },
    {
      title: '创建开始时间',
      dataIndex: 'createStartTime',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={val => {
              setCreateStartTime(val);
              onChange(val);
            }}
            disabledDate={disabledStartDate}
            value={value}
          />
        );
      }
    },
    {
      title: '创建结束时间',
      dataIndex: 'createEndTime',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={val => {
              setCreateEndTime(val);
              onChange(val);
            }}
            disabledDate={disabledEndDate}
            value={value}
          />
        );
      }
    },
    {
      title: '结案状态',
      dataIndex: 'isClose',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => <Checkbox checked={value} onChange={onChange}>可结案</Checkbox>,
    },
  ] : [
    {
      title: '多收编号',
      dataIndex: 'accidentId',
      width: 200,
      fixed: 'left',
    },
    {
      title: '创建航站',
      dataIndex: 'enterTerminal',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          showSearch
          placeholder="请选择"
          value={value}
          onChange={onChange}
          optionFilterProp="children"
        >
          {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
        </Select>
      ),
    },
    {
      title: '行李属性',
      dataIndex: 'pkgProperty',
      width: 100,
      filters: false,
      valueEnum: Const.pkgPropertyMap,
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width: 80,
      renderFormItem: (_, { value, onChange }) => {
        return <Input
          onChange= {e => {
            let value = Const.formatFlightNo(e.target.value);
            onChange(value);
          }}
          value={value}
          allowClear
          maxLength={6}
          placeholder="3U" />;
      }
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={onChange}
            disabledDate={disabledDate}
            value={value}
          />
        );
      }
    },
    {
      title: '少收编号',
      dataIndex: 'underchargeAccidentId',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '行李牌号',
      dataIndex: 'pkgNo',
      width: 120,
    },
    {
      title: 'WT编号',
      dataIndex: 'wtCode',
      width: 120,
    },
    {
      title: '旅客姓名',
      dataIndex: 'paxName',
      width: 100,
    },
    {
      title: '证件类型',
      dataIndex: 'idType',
      width: 100,
      render: (text, record) => <span>{Const.idTypeMap[text]?.text || '-'}</span>,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          placeholder="请选择"
          value={value}
          onChange={onChange}
        >
          {Const.idTypeListForSearch.map(item => <Option key={item.value} value={item.value}>{item.label}</Option>)}
        </Select>
      ),
    },
    {
      title: '证件号',
      dataIndex: 'idNo',
      width: 200,
    },
    {
      title: '行李特征',
      dataIndex: 'pkgType',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '事故单状态',
      dataIndex: 'status',
      width: 120,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          placeholder="请选择"
          value={value}
          onChange={onChange}
          mode="multiple"
        >
          {Const.jieanStatusList.map(item => <Option key={item.value} value={item.value}>{item.label}</Option>)}
        </Select>
      ),
    },
    {
      title: '客票号',
      dataIndex: 'tktNo',
      width: 200,
    },
    {
      title: '图片管理',
      dataIndex: 'picture',
      width: 100,
      hideInSearch: true,
      render: (_, record) => (
        <span>图片管理</span>
      )
    },
    {
      title: '结案状态',
      dataIndex: 'pkgStatus',
      width: 100,
      hideInSearch: true,
      render: (text, record) => (
        <span>{+text === 1 ? '已结案' : '未结案'}</span>
      )
    },
    {
      title: '入库人',
      dataIndex: 'insertUser',
      width: 120,
      hideInSearch: true
    },
    {
      title: '创建人',
      dataIndex: 'createUser',
      width: 120,
    },
    {
      title: '出库类型',
      dataIndex: 'outType',
      width: 120,
      valueEnum: Const.outTypeMap,
      filters: false
    },
    {
      title: '自提状态',
      dataIndex: 'recipientStatus',
      width: 120,
      hideInSearch: true,
      valueEnum: Const.recipientStatusMap,
      filters: false
    },
    {
      title: '创建开始时间',
      dataIndex: 'createStartTime',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={val => {
              setCreateStartTime(val);
              onChange(val);
            }}
            disabledDate={disabledStartDate}
            value={value}
          />
        );
      }
    },
    {
      title: '创建结束时间',
      dataIndex: 'createEndTime',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={val => {
              setCreateEndTime(val);
              onChange(val);
            }}
            disabledDate={disabledEndDate}
            value={value}
          />
        );
      }
    },
  ];

  return (
    <>
      {!getUserServiceCityLoading && <ProTable
        actionRef={actionRef}
        formRef={ref}
        className={styles.compactTable}
        rowKey="accidentId"
        rowSelection={rowSelection}
        headerTitle="进港少收行李管理"
        toolBarRender={() => PrivateData.toolBarRenderArr.map((item, index) => {
          let isShow = false;
          for (let authItem of item.authCode) {
            if (AuthComponent.getAuth(authItem)) {
              isShow = true;
              break;
            }
          }
          if (isShow) {
            return <Button
              key={index}
              type="primary"
              disabled={item.disabled || isLessOrMore === 'more'}
              size="small"
              onClick={() => headerTitleClick(item.value)}>
              {item.text}
            </Button>;
          }
        })}
        onSubmit={() => {
          setSelectedRowKeys([]);
          setSelectedRows([]);
        }}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        onReset={onReset}
        request={params => {
          if (PrivateData.isFirst) {
            PrivateData.isFirst = false;
            if (state?.accidentId && PrivateData.isFrom) {
              PrivateData.isFrom = false;
              params = {
                accidentId: state?.accidentId || ''
              }
            } else {
              params.flightDate = moment().format(Const.format);
              params.createStartTime = moment().format(Const.format);
              params.createEndTime = moment().format(Const.format);
              params.enterTerminal = userServiceCity;
              params.serviceCity = userServiceCity;
              params.status = '0,1,2';
            }
          } else {
            const isFromCompensate = sessionStorage.getItem('isFromCompensate') || '';
            if (isFromCompensate === '1') {
              sessionStorage.setItem('isFromCompensate', '0');
              params = {
                accidentId: state?.accidentId || ''
              }
            } else {
              let arr = ['flightDate', 'createStartTime', 'createEndTime'];
              for (let item of arr) {
                if (params[item] && params[item].isValid()) {
                  params[item] = moment(params[item]).format(Const.format)
                }
              }
              if (params.status && params.status.length !== 0) {
                params.status = params.status.join(',');
              }
              params.isClose = params.isClose ? 1 : '';
            }
          }

          if (PrivateData.isLessOrMore === 'less') {
            setSearchData(params);
            return listUnderchargeLuggage(params);
          } else {
            params.pkgNo = PrivateData.pkgNo || '';
            return listOverchargeLuggage(params);
          }

        }}
        tableAlertRender={false}
        columns={columns}
        options={false}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
        }}
        scroll={{ x: 900, y: height }}
        search={{
          searchText: (
            <span ref={searchRef}>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val);
          },
          span: { // 设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          }
        }}
      >
      </ProTable>}
      <QuickRetrievalPopup
        modalVisible={quickRetrievalVisible}
        onCancel={quickRetrievalCancel}
        onSubmit={quickRetrievalSubmit}
        ownerType={PrivateData.ownerType}
        selectCityData={selectCityData}
      ></QuickRetrievalPopup>
      <ExpressInfo
        modalVisible={expressInfoVisible}
        onCancel={expressInfoCancel}
        onSubmit={expressInfoSubmit}
        itemData={itemData}
        ownerType={PrivateData.ownerType}
      ></ExpressInfo>
      <HistoryRecord
        modalVisible={historyRecordVisible}
        onCancel={historyRecordCancel}
        onSubmit={historyRecordSubmit}
        accidentId={itemData.accidentId}
        ownerType={PrivateData.ownerType}
      ></HistoryRecord>
      <CompensationList
        modalVisible={compensationListVisible}
        onCancel={compensationListCancel}
        onSubmit={compensationListSubmit}
        itemData={itemData}
        ownerType={PrivateData.ownerType}
        compensateType={compensateType}
      ></CompensationList>
      <AccidentReason
        modalVisible={accidentReasonVisible}
        onCancel={accidentReasonCancel}
        onSubmit={accidentReasonSubmit}
        accidentId={itemData.accidentId}
        ownerType={PrivateData.ownerType}
      ></AccidentReason>
      <AllAccidentReason
        modalVisible={allAccidentReasonVisible}
        onCancel={allAccidentReasonCancel}
        onSubmit={allAccidentReasonSubmit}
        accidentList={accidentList}
        ownerType={PrivateData.ownerType}
      ></AllAccidentReason>
      {lostItemPicVisible && <PicUpload
        onSubmit={async value => {
          const success = await handleImgs(value)
        }}
        onCancel={() => handleLostItemPicVisible(false)}
        lostItemPicVisible={lostItemPicVisible}
        lostItemPic={lostItemPic}
        ownerType={PrivateData.ownerType}
      ></PicUpload>}
      {lostItemPicManageVisible && <ShowPic
        onSubmit={async value => {
          const success = await handleDelImgs(value)
        }}
        toUpload={(value) => {
          handleLostItemPicture(value)
          handleLostItemPicManageVisible(false)
          handleLostItemPicVisible(true)
        }}
        onCancel={() => handleLostItemPicManageVisible(false)}
        lostItemPicManageVisible={lostItemPicManageVisible}
        lostItemPic={lostItemPic}
        ownerType={PrivateData.ownerType}
        status={itemData.status}
      ></ShowPic>}
    </>
  )
}

export default Form.create()(LessBaggageManagement);
